package com.meitianhui.convenitenbuy.base;

import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StatusBarUtil;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.NoScrollWebView;
import com.meitianhui.convenitenbuy.widget.dialog.ShareDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

/**
 * webview页面基类
 */

public abstract class BaseWebViewActivity extends BaseActivity {
    public WebChromeClient.CustomViewCallback mCallback = null;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    private ImageView mTbBackAll;
    public TextView mTb_title;
    private ImageView mToolbarIvMenu;
    private TextView mToolbarTvMenu;
    private LinearLayout mToolbarMenu;
    public NoScrollWebView mWebView;
    public ProgressBar mProgressBar;
    public String url;
    public String mTitle;
    private UMImage mUmImage;
    private ShareDialog mShareDialog;
    public String mShareTitle = "", mShareDesc = "", mShareImgPath = "", mShareUrl = "";//分享数据
    public String mCurrentName = "";


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_base_webview);
        setTranslucentStatus(R.color.white);
        StatusBarUtil.StatusBarLightMode(this);

        initID();
        initRxClick();
        setTbBackAllInVisible();
        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            mProgressBar.setVisibility(View.VISIBLE);
            mWebView.loadUrl(url);
            mWebView.setWebChromeClient(new MyWebChromeClient());
            onRefreshData();
        });

    }

    protected void isEnable(boolean refresh) {
        mSwipeRefreshLayout.setEnabled(refresh);
    }

    /**
     * 设置刷新完成
     */
    protected void refreshFinish() {
        mSwipeRefreshLayout.setRefreshing(false);
    }


    protected void initRxClick() {
        RxUtils.bindEvents(mTbBackAll, this);
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.toolbar_back_all:
                isFinish();
                break;
            case R.id.toolbar_menu:
                clickMenu();
                break;
        }
    }

    /**
     * 菜单按钮的点击事件
     */
    protected void clickMenu() {


    }

    protected void initID() {
        mSwipeRefreshLayout = getViewById(R.id.swipe_refresh_layout);
        mTbBackAll = getViewById(R.id.toolbar_back_all);
        mTb_title = getViewById(R.id.toolbar_title);
        mToolbarIvMenu = getViewById(R.id.toolbar_iv_menu);
        mToolbarTvMenu = getViewById(R.id.toolbar_tv_menu);
        mToolbarMenu = getViewById(R.id.toolbar_menu);
        mWebView = getViewById(R.id.webview);
        mProgressBar = getViewById(R.id.pb);
        initData();
        webViewSet();
    }

    private void initData() {
        url = getIntent().getStringExtra("url");
        mTitle = getIntent().getStringExtra("title");
    }

    private void webViewSet() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.loadUrl(url);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.setWebContentsDebuggingEnabled(true);
        }
    }

    /**
     * 设置返回键不可见
     */
    protected void setTbBackAllInVisible() {
        if (isHideTbBack()) {
            mTbBackAll.setVisibility(View.INVISIBLE);
            mTbBackAll.setEnabled(false);
        }

    }

    /**
     * 设置菜单按钮可不可见
     * 文字 --> text为String
     * 图片 -->  返回R.mipmap.XXX即可
     */
    protected void setTbMenu(Object text) {
        if (text != null)
            if (text instanceof String) {
                mToolbarIvMenu.setVisibility(View.INVISIBLE);
                mToolbarTvMenu.setVisibility(View.VISIBLE);
                mToolbarTvMenu.setText((String) text);
                RxUtils.bindEvents(mToolbarMenu, this);
            } else if (text instanceof Integer) {
                mToolbarTvMenu.setVisibility(View.INVISIBLE);
                mToolbarIvMenu.setVisibility(View.VISIBLE);
                mToolbarIvMenu.setImageResource((int) text);
                RxUtils.bindEvents(mToolbarMenu, this);
            }
    }

    protected void setTbTitle(String title) {
        if (title != null)
            mTb_title.setText(title);
    }


    public void share(String typeOfShare) {
        if (mUmImage == null)
            mUmImage = new UMImage(this, R.mipmap.logo);
            mShareDialog = new ShareDialog(this, onShareClickListener,typeOfShare);
            mShareDialog.show();
    }

    ShareDialog.OnShareClickListener onShareClickListener = new ShareDialog.OnShareClickListener() {

        @Override
        public void FriendCircle(View v) {
            UMWeb web;
            if (url.contains("detail") || url.contains("publish")) {
                web = new UMWeb(mShareUrl);
                web.setTitle(mShareTitle);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            } else {
                web = new UMWeb(url + "&s=1");
                web.setTitle(mCurrentName);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            }
            new ShareAction(BaseWebViewActivity.this)
                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                    .setCallback(shareListener)
                    .withMedia(web)
                    .share();
            mShareDialog.dismiss();

        }

        @Override
        public void WeChatFriends(View v) {
            UMWeb web;
            if (url.contains("detail") || url.contains("publish")) {
                web = new UMWeb(mShareUrl);
                web.setTitle(mShareTitle);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            } else {
                web = new UMWeb(url + "&s=1");
                web.setTitle(mCurrentName);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            }
            new ShareAction(BaseWebViewActivity.this)
                    .setPlatform(SHARE_MEDIA.WEIXIN)
                    .setCallback(shareListener)
                    .withMedia(web)
                    .share();
        }

        @Override
        public void QQFriends(View v) {
            UMWeb web;
            if (url.contains("detail") || url.contains("publish")) {
                web = new UMWeb(mShareUrl);
                web.setTitle(mShareTitle);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            } else {
                web = new UMWeb(url + "&s=1");
                web.setTitle(mCurrentName);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            }
            new ShareAction(BaseWebViewActivity.this)
                    .setPlatform(SHARE_MEDIA.QQ)
                    .setCallback(shareListener)
                    .withMedia(web)
                    .share();

        }

        @Override
        public void QQZone(View v) {
            UMWeb web;
            if (url.contains("detail") || url.contains("publish")) {
                web = new UMWeb(mShareUrl);
                web.setTitle(mShareTitle);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            } else {
                web = new UMWeb(url + "&s=1");
                web.setTitle(mCurrentName);//标题
                web.setThumb(mUmImage);  //缩略图
                web.setDescription(mShareDesc);//描述
            }
            new ShareAction(BaseWebViewActivity.this)
                    .setPlatform(SHARE_MEDIA.QZONE)
                    .setCallback(shareListener)
                    .withMedia(web)
                    .share();

        }

        /**
         * 微信小程序分享
         * @param v
         */
        @Override
        public void WxMini(View v) {
            //暂时还是在这个类里面去写
            shareWxMini(v);

        }
    };


    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            TipUtils.showToast(App.getInstance(), "成功了");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            TipUtils.showToast(App.getInstance(), "失败" + t.getMessage());
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            TipUtils.showToast(App.getInstance(), "取消了");
        }
    };


    public class WebViewClient extends android.webkit.WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if(error.getPrimaryError() == android.net.http.SslError.SSL_INVALID ){  //https 忽略
                handler.proceed();
            }else{
                handler.cancel();
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
            view.loadUrl("");
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            urlLoading(view, url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String s_url) {
            if (s_url.startsWith("http")) {
                url = s_url;
            }
            pageFinish(view,s_url);
        }
    }

    public void pageFinish(WebView view, String s_url){

    }

    public class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
            if (newProgress == 100) {
                mProgressBar.setVisibility(View.INVISIBLE);
                refreshFinish();
            }
            super.onProgressChanged(view, newProgress);
        }

        public View getVideoLoadingProgressView() {
            return loadingProgressView(App.getInstance());
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (mCallback != null) {
                mCallback.onCustomViewHidden();
                mCallback = null;
                return;
            }
            mCallback = callback;
        }

        @Override
        public void onHideCustomView() {
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            receivedTitle(view, title);
            super.onReceivedTitle(view, title);
        }
    }

    @Override
    protected void onDestroy() {
        if( mWebView!=null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        super.onDestroy();
    }


    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (isDestroyed()) return;
    }

    public View loadingProgressView(Context context) {
        return new ProgressBar(context);
    }

    /**
     * 返回按钮默认是不隐藏的
     */
    protected boolean isHideTbBack() {
        return false;
    }

    protected abstract void urlLoading(WebView view, String url);

    protected abstract void receivedTitle(WebView view, String title);

    protected abstract void onRefreshData();

    protected abstract void isFinish();

    protected abstract void shareWxMini(View v);


}
